<template>
  <el-form ref="ruleForm" :model="form" label-width="80px" style="margin: 0 auto;width:100%;">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="目录">
          <el-input v-model="gysName" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="文件" prop="gysId">
          <el-upload
            class="upload-demo"
            :action="uploadpath"
            :headers="uoloadheaders"
            :on-success="handleAvatarSuccess"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :before-upload="beforeAvatarUpload"
            name="uploadfile_ant"
          >
            <el-button size="small" icon="el-icon-upload" type="primary">选择文件</el-button>
            <span style="color:red;">  上传文件不超过100m</span>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="文件标签" prop="name">
          <el-input v-model="fileLabel" placeholder="文件标签，用';'隔开" />
        </el-form-item>
      </el-col>
    </el-row>
    <div style="text-align:center;">
      <el-button type="primary" :disabled="upVisible" @click="save('ruleForm')">确定</el-button>
      <el-button type="danger" @click="closePage">取消</el-button>
    </div>
  </el-form>
</template>

<script>

import { getAllLeafNode2 } from '@/api/catalogDetail'
import { saveData } from '@/api/publicFile'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
import { getId } from '@/api/user'

export default {
  inject: ['getList'],
  props: { // 第二种方式
    link: {
      type: String,
      required: true
    },
    flag: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      form: {},
      gysName: '',
      loading: '',
      uploadpath: '',
      name: '',
      batchCode: '',
      dialogImageUrl: '',
      fileLabel: '',
      uoloadheaders: {},
      dialogVisible: false,
      upVisible: true,
      visitPath: null,
      disabled: false,
      ggTypes: [],
      fileData: '', // 文件上传数据（多文件合一）
      fileList: [] // upload多文件数组
    }
  },
  mounted() {
    this.form.gftId = this.link
    this.getDetailed()
  },
  methods: {
    getDetailed() {
      getAllLeafNode2({ code: this.link }).then(response => {
        this.gysName = response.data.typeName
      }).catch(function() {
      })

      this.batchCode = ''
      getId().then(response => {
        this.batchCode = response.data

        var path = '/publicFile/uploadFile?gftId=' + this.link + '&batchCode=' + this.batchCode
        this.uploadpath = process.env.VUE_APP_BASE_API + path
        this.uoloadheaders = { 'X-Token': getToken() }
      })
    },
    handleAvatarSuccess(res, file) {
      this.loading.close()
      if (res.code === 20000) {
        this.form = res.data
        this.upVisible = false
      } else {
        this.upVisible = false
        Message({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000
        })
      }
    },
    // 移除
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 100

      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过100MB!')
      }
      this.loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return isLt2M
    },
    // 选取文件超过数量提示
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 监控上传文件列表
    handleChange(file, fileList) {
      const existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
      if (existFile) {
        this.$message.error('当前文件已经存在!')
        fileList.pop()
      }
      this.fileList = fileList
    },
    // 确认添加问题
    async save() {
      if (this.fileList.length > 0) {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })

            this.form.fileLabel = this.fileLabel
            this.form.type = 'M'
            this.form.approvelState = '2'
            saveData(this.form).then(response => {
              Message({
                message: '新增成功',
                type: 'success',
                duration: 5 * 1000
              })
              this.$emit('update:visible', false)
              this.getList()
              loading.close()
            }).catch(response => {
              this.getList()
              loading.close()
            })
          } else {
            return false
          }
        })
      } else {
        Message({
          message: '请先上传文件！',
          type: 'error',
          duration: 5 * 1000
        })
      }
    },
    closePage() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style scoped>

.el-button--primary.is-disabled, .el-button--primary.is-disabled:hover, .el-button--primary.is-disabled:focus, .el-button--primary.is-disabled:active {
    color: #FFFFFF;
    background-color: #8cc8ff;
    border-color: #8cc8ff;
}
</style>
